<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import EZUIKit from 'ezuikit-js';
import eventBus from '@/utils/eventBus';
import { getCameraUrlAndToken, captureImage } from '@/api/camera';
import { ElMessage } from 'element-plus';

export default {
  name: 'CenterTop',
  setup() {
    let player;
    const isPlaying = ref(true);
    const isSoundOn = ref(true);
    const playerReady = ref(false);
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 3;
    let autoSnapshotTimer = null;

    // 自动抓拍功能
    const startAutoSnapshot = () => {
      if (autoSnapshotTimer) {
        clearInterval(autoSnapshotTimer);
      }
      
      // 设置10分钟的定时器，并且只在播放器就绪且正在播放时执行抓拍
      autoSnapshotTimer = setInterval(() => {
        if (playerReady.value && isPlaying.value) {  // 检查播放状态
          takeSnapshot();
        }
      }, 600000);
    };

    // 停止自动抓拍
    const stopAutoSnapshot = () => {
      if (autoSnapshotTimer) {
        clearInterval(autoSnapshotTimer);
        autoSnapshotTimer = null;
      }
    };

    // 播放/停止控制
    const togglePlay = async () => {
      if (!playerReady.value || !player) {
        console.log('播放器未就绪');
        return;
      }

      try {
        if (isPlaying.value) {
          const result = await player.stop();
          console.log('停止播放结果:', result);
          isPlaying.value = false;
          stopAutoSnapshot(); // 停止播放时停止自动抓拍
        } else {
          const result = await player.play();
          console.log('开始播放结果:', result);
          isPlaying.value = true;
          startAutoSnapshot(); // 开始播放时启动自动抓拍
        }
      } catch (err) {
        console.error('播放控制失败:', err);
        initPlayer();
      }
    };

    // 声音控制
    const toggleSound = async () => {
      try {
        if (isSoundOn.value) {
          const result = await player.closeSound();
          console.log('关闭声音结果:', result);
        } else {
          const result = await player.openSound();
          console.log('开启声音结果:', result);
        }
        isSoundOn.value = !isSoundOn.value;
      } catch (err) {
        console.error('声音控制失败:', err);
      }
    };

    // 拍照功能
    const takeSnapshot = async () => {
      if (!playerReady.value || !player) {
        console.log('播放器未就绪');
        return;
      }

      try {
        // 调用后端抓拍接口
        const result = await captureImage('AB9831171');
        console.log('抓拍结果:', result);

        if (result.code === 200 && result.data?.url) {
          // 发送新照片事件
          eventBus.emit('new-photo', result.data.url);
          console.log('抓拍成功:', result.data.url);
          ElMessage.success('抓拍成功');
        } else {
          throw new Error(result.message || '抓拍失败');
        }
      } catch (error) {
        console.error('抓拍失败:', error);
        ElMessage.error(error.message || '抓拍失败');
      }
    };

    // 初始化播放器
    const initPlayer = async () => {
      if (player) {
        try {
          player.destroy();
        } catch (err) {
          console.error('销毁播放器失败:', err);
        }
      }

      playerReady.value = false;

      try {
        // 从后端获取摄像头配置
        const cameraRes = await getCameraUrlAndToken('AB9831171');
        console.log('Camera config:', cameraRes);

        if (cameraRes.code === 200 && cameraRes.data) {
          const initOptions = {
            id: 'video-container',
            accessToken: cameraRes.data.accessToken,
            url: cameraRes.data.url,
            template: 'simple',
            width: 650,
            height: 410,
            autoplay: true,
            handleError: (err) => {
              console.error('播放器错误:', err);
              playerReady.value = false;
              if (err.retcode === 1003 && reconnectAttempts < maxReconnectAttempts) {
                console.log(`尝试重新连接... (${reconnectAttempts + 1}/${maxReconnectAttempts})`);
                reconnectAttempts++;
                setTimeout(() => {
                  initPlayer();
                }, 2000);
              }
            },
            handleSuccess: () => {
              console.log('播放器初始化成功');
              playerReady.value = true;
              isPlaying.value = true;
              reconnectAttempts = 0;
            },
            env: {
              domain: 'https://open.ys7.com',
            },
            plugin: ['talk'],
            audio: true,
            controls: false,
            controlBar: {
              quality: false
            }
          };

          try {
            player = new EZUIKit.EZUIKitPlayer(initOptions);
          } catch (err) {
            console.error('播放器创建失败:', err);
            ElMessage.error('播放器创建失败');
          }
        } else {
          throw new Error(cameraRes.message || '获取摄像头配置失败');
        }
      } catch (error) {
        console.error('初始化播放器失败:', error);
        ElMessage.error(error.message || '初始化播放器失败');
      }
    };

    onMounted(() => {
      initPlayer();
      startAutoSnapshot();
    });

    onBeforeUnmount(() => {
      stopAutoSnapshot(); // 组件卸载时停止自动抓拍
      if (player) {
        try {
          player.destroy();
        } catch (err) {
          console.error('销毁播放器失败:', err);
        }
      }
    });

    return {
      isPlaying,
      isSoundOn,
      playerReady,
      togglePlay,
      toggleSound,
      takeSnapshot
    };
  }
}
</script>
<template>
  <div class="center-top">
    <dv-border-box-11 :color="['#00ffd9', 'rgba(0, 255, 217, 0.3)']">
      <div class="content-wrapper">
        <div class="header">
          <div class="title-container">
              <div class="title">智慧大棚实时监控</div>
          </div>
        </div>
        <div id="video-container" class="video-container"></div>
        <!-- 控制按钮 -->
        <div class="control-buttons">
          <dv-border-box-12 class="button-border" :color="['#00ffd9', 'rgba(0, 255, 217, 0.3)']">
            <div class="button" @click="togglePlay">
              {{ isPlaying ? '停止' : '播放' }}
            </div>
          </dv-border-box-12>
          <dv-border-box-12 class="button-border" :color="['#00ffd9', 'rgba(0, 255, 217, 0.3)']">
            <div class="button" @click="toggleSound">
              {{ isSoundOn ? '关闭声音' : '开启声音' }}
            </div>
          </dv-border-box-12>
          <dv-border-box-12 class="button-border" :color="['#00ffd9', 'rgba(0, 255, 217, 0.3)']">
            <div class="button" @click="takeSnapshot">
              拍照
            </div>
          </dv-border-box-12>
        </div>
      </div>
    </dv-border-box-11>
  </div>
</template>

<style scoped>
.center-top {
  width: 100%;
  height: 100%;
  padding: 0;
}

.content-wrapper {
  width: 100%;
  height: 100%;
  padding: 8px;
  border-radius: 4px;
  position: relative;
  background: rgba(0, 28, 36, 0.3);
}

.video-container {
  width: 100%;
  height: 300px;
}

/* 控制按钮样式 */
.control-buttons {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 70px;
  z-index: 100;
}

.button-border {
  width: 120px;
  height: 40px;
  position: relative;
}

.button {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #00ffd9;
  cursor: pointer;
  font-size: 18px;
  font-weight: bold;
  text-shadow: 0 0 10px rgba(0, 255, 217, 0.3);
}

/* 添加点击特效 */
.button:active {
  transform: scale(0.95);
  color: #ffffff;
}

.button-border::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 255, 217, 0.2);
  opacity: 0;
  pointer-events: none;
}

.button:active + .button-border::after {
  opacity: 1;
  animation: ripple 0.4s ease-out;
}

@keyframes ripple {
  from {
    transform: scale(0);
    opacity: 1;
  }
  to {
    transform: scale(2);
    opacity: 0;
  }
}

.header {
  margin-bottom: 8px;
  width: 100%;
}

.title-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.title {
  color: #00ffd9;
  font-size: 20px;
  font-weight: bold;
  white-space: nowrap;
  padding: 0 10px;
  line-height: 40px;
  text-shadow: 0 0 10px rgba(0, 255, 217, 0.3);
}

/* 修改按钮悬停效果 */
.button:hover {
  color: #fff;
  text-shadow: 0 0 15px rgba(0, 255, 217, 0.5);
}
</style>